import * as types from '../mutation-types'
import { REDWINEPRODUCTID, CIGARPRODUCTID } from '@/config/product-id'
import api from '@/api'
import _ from 'lodash'

// state
const state = {
  deviceList: [],
  currentDevice: {},
  currentSocket: null,
  socketList: [],
  uiDeviceList: [],
  uiDevice: null
}

// 1: 获取设备列表
// 2: 过滤红酒柜和雪茄柜
// 3: 建立socket
// 4: 数据上报
// getters
const getters = {
  // 设备列表
  deviceList: state => {
    return state.deviceList
  },

  // 红酒柜设备列表
  redWineDeviceList: state => {
    return _.filter(state.deviceList, device => {
      return device.device_pid === REDWINEPRODUCTID
    })
  },

  // 雪茄柜设备列表
  cigarDeviceList: state => {
    return _.filter(state.deviceList, device => {
      return device.device_pid === CIGARPRODUCTID
    })
  },

  // 当前设备
  currentDevice: state => {
    return state.currentDevice
  },

  // 当前连接实例
  currentSocket: state => {
    return state.currentSocket
  },

  // 连接实例设备列表
  socketList: state => {
    return state.socketList
  },

  // 渲染列表
  uiDeviceList: state => {
    return state.uiDeviceList
  },

  // 渲染当前设备
  uiDevice: state => {
    return state.uiDevice
  }
}

// actions
const actions = {
  // 获取设备列表
  async fetchDeviceList ({commit, state}) {
    let { data: {devices} } = await api.getDeviceList()
    commit(types.DEVICE_LIST, devices)
  },
  // 获取当前连接实例
  currentSocket ({commit}, currentSocket) {
    commit(types.CURRENT_SCOKET, currentSocket)
  },
  // 实例设备列表
  socketList ({commit}, socketList) {
    commit(types.SCOKET_LIST, socketList)
  },
  // 渲染设备列表
  uiDeviceList ({commit}, uiDeviceList) {
    commit(types.UIDEVICELIST, uiDeviceList)
  },

  // 渲染设备
  uiDevice ({commit}, uiDevice) {
    commit(types.UIDEVICE, uiDevice)
  }
}

// mutations
const mutations = {
  [types.DEVICE_LIST] (state, fetch) {
    state.deviceList = fetch
  },
  [types.CURRENT_DEVICE] (state, currentDevice) {
    state.currentDevice = currentDevice
  },
  [types.CURRENT_SCOKET] (state, currentSocket) {
    state.currentSocket = currentSocket
  },
  [types.SCOKET_LIST] (state, socketList) {
    state.socketList = socketList
  },
  [types.UIDEVICELIST] (state, uiDeviceList) {
    state.uiDeviceList = uiDeviceList
  },
  [types.UIDEVICE] (state, uiDevice) {
    state.uiDevice = uiDevice
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
